#include "os.h"

#define WIN32_LEAN_AND_MEAN
#include <windows.h>


#define SEM_WAIT_INFINITE ((unsigned int)(-1))

int		OS_Init() 
{
	return 0;
}

void	OS_UnInit()
{
}

psem_t	OS_SemCreate(int nval)
{
	psem_t h = CreateSemaphore(NULL,nval,0x0fffffff,NULL);
	return h;
}

void	OS_SemDestroy(psem_t pSem)
{
	CloseHandle(pSem);
}

void	OS_SemSignal(psem_t pSem)
{
	if(!pSem)
		return;

	ReleaseSemaphore(pSem,1,NULL);
}

/*0,suc, or time-out*/
int		OS_SemWait(psem_t pSem,unsigned int	nWaitMinisecs)
{
	if(!pSem)
		return 0;
	if(WaitForSingleObject(pSem,nWaitMinisecs) != WAIT_OBJECT_0)
		return -1;

	return 0;
}

pthread_t OS_ThreadCreate(THREADFUNC pFunc,int nPrio,int nStackSize,void* lparam)
{
	pthread_t h = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)pFunc,lparam,0,NULL);
	return h;
}

void	OS_ThreadJoin(pthread_t tThread)
{
	if(!tThread)
		return;

	WaitForSingleObject(tThread,SEM_WAIT_INFINITE/*INFINITE*/);
}

void	OS_ThreadCancel(pthread_t tThread)
{
	if(tThread)
		TerminateThread(tThread,0);
}

void	OS_ThreadDestroy(pthread_t tThread)
{
	if(tThread)
	{
		if(WaitForSingleObject(tThread,100) != WAIT_OBJECT_0)
			OS_ThreadCancel(tThread);
		CloseHandle(tThread);
	}
}


void	OS_Sleep(unsigned long dwSecs)
{
	Sleep(dwSecs * 1000*1000);
}

void    OS_USleep(unsigned int nMiniSecs)
{
	Sleep(nMiniSecs);
}


